<template>
  <div class="textbook-detail" v-loading="loading">
    <el-card v-if="textbook">
      <el-row :gutter="20">
        <el-col :span="10">
          <div class="image-container">
            <el-image
              :src="getMainImage()"
              fit="cover"
              :preview-src-list="getImageList()"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </el-col>
        <el-col :span="14">
          <div class="detail-info">
            <h1 class="title">{{ textbook.title }}</h1>
            <div class="meta-info">
              <p><strong>作者:</strong> {{ textbook.author || '未知' }}</p>
              <p><strong>出版社:</strong> {{ textbook.publisher || '未知' }}</p>
              <p><strong>ISBN:</strong> {{ textbook.isbn || '未知' }}</p>
              <p><strong>分类:</strong> {{ textbook.category_name || '未分类' }}</p>
              <p><strong>成色:</strong> 
                <el-tag :type="getConditionType(textbook.condition)">
                  {{ getConditionText(textbook.condition) }}
                </el-tag>
              </p>
              <p><strong>卖家:</strong> {{ textbook.seller_name }}</p>
              <p><strong>联系电话:</strong> {{ textbook.seller_phone || '未提供' }}</p>
            </div>
            <div class="price-info">
              <span class="current-price">¥{{ textbook.price }}</span>
              <span class="original-price" v-if="textbook.original_price">
                原价: ¥{{ textbook.original_price }}
              </span>
            </div>
            <div class="status-info">
              <el-tag :type="textbook.status === 'on_sale' ? 'success' : 'info'" size="large">
                {{ textbook.status === 'on_sale' ? '在售' : textbook.status === 'sold' ? '已售' : '下架' }}
              </el-tag>
            </div>
            <div class="actions" v-if="textbook.status === 'on_sale'">
              <el-button type="primary" size="large" class="buy-button" @click="handleBuy">
                立即购买
              </el-button>
              <el-button size="large" @click="$router.back()">返回</el-button>
            </div>
            <div class="views">
              <span>浏览量: {{ textbook.views || 0 }}</span>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <div class="description">
        <h3>教材描述</h3>
        <p>{{ textbook.description || '暂无描述' }}</p>
      </div>
    </el-card>
    
    <!-- 购买对话框 -->
    <el-dialog
      v-model="showOrderDialog"
      title="确认购买"
      width="500px"
    >
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="教材名称">
          <el-input v-model="textbook.title" disabled />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="textbook.price" disabled />
        </el-form-item>
        <el-form-item label="收货人" required>
          <el-input v-model="orderForm.buyer_name" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="orderForm.buyer_phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="收货地址" required>
          <el-input
            v-model="orderForm.buyer_address"
            type="textarea"
            :rows="3"
            placeholder="请输入收货地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showOrderDialog = false">取消</el-button>
        <el-button type="primary" @click="createOrder" :loading="orderLoading">确认购买</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { useUserStore } from '../store/user'
import { textbookApi } from '../api/textbook'
import { orderApi } from '../api/order'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const orderLoading = ref(false)
const textbook = ref(null)
const showOrderDialog = ref(false)
const orderForm = reactive({
  buyer_name: '',
  buyer_phone: '',
  buyer_address: '',
  remark: ''
})

// 加载教材详情
const loadTextbook = async () => {
  loading.value = true
  try {
    const response = await textbookApi.getTextbookById(route.params.id)
    if (response.success) {
      textbook.value = response.data
    } else {
      ElMessage.error('加载教材详情失败')
      router.push('/textbooks')
    }
  } catch (error) {
    console.error('加载教材详情失败:', error)
    ElMessage.error('加载教材详情失败')
    router.push('/textbooks')
  } finally {
    loading.value = false
  }
}

// 导入默认图片
import mathTextbook from '@/assets/images/math_textbook.svg'
import englishTextbook from '@/assets/images/english_textbook.svg'
import computerTextbook from '@/assets/images/computer_textbook.svg'
import physicsTextbook from '@/assets/images/physics_textbook.svg'

// 获取主图片
const getMainImage = () => {
  if (textbook.value && textbook.value.images && textbook.value.images.length > 0) {
    return textbook.value.images[0]
  }
  // 根据教材类别显示默认图片
  if (textbook.value && textbook.value.category_name) {
    const categoryImages = {
      '数学': mathTextbook,
      '英语': englishTextbook,
      '计算机': computerTextbook,
      '物理': physicsTextbook
    }
    return categoryImages[textbook.value.category_name] || ''
  }
  return ''
}

// 获取图片列表
const getImageList = () => {
  if (textbook.value && textbook.value.images && textbook.value.images.length > 0) {
    return textbook.value.images
  }
  return [getMainImage()]
}

// 获取成色类型
const getConditionType = (condition) => {
  const types = {
    'new': 'success',
    'like_new': 'info',
    'good': '',
    'fair': 'warning',
    'poor': 'danger'
  }
  return types[condition] || ''
}

// 获取成色文本
const getConditionText = (condition) => {
  const texts = {
    'new': '全新',
    'like_new': '九成新',
    'good': '八成新',
    'fair': '七成新',
    'poor': '六成新'
  }
  return texts[condition] || '未知'
}

// 处理购买点击
const handleBuy = () => {
  // 检查用户是否已登录
  if (!userStore.currentUser && !localStorage.getItem('user')) {
    // 未登录状态，跳转到登录页面
    ElMessage.info('请先登录再购买教材')
    router.push('/login')
  } else {
    // 已登录状态，显示订单对话框
    showOrderDialog.value = true
  }
}

// 创建订单
const createOrder = async () => {
  if (!orderForm.buyer_name || !orderForm.buyer_phone || !orderForm.buyer_address) {
    ElMessage.warning('请填写完整的收货信息')
    return
  }
  
  // 检查用户登录状态
  const userStr = localStorage.getItem('user')
  if (!userStr) {
    ElMessage.error('用户信息丢失，请重新登录')
    router.push('/login')
    return
  }
  
  // 从本地存储获取当前用户ID
  let buyerId = 1 // 默认值，以防获取失败
  try {
    const user = JSON.parse(userStr)
    buyerId = user.user_id || user.id
  } catch (e) {
    console.error('解析用户数据失败:', e)
    ElMessage.error('用户信息解析失败，请重新登录')
    router.push('/login')
    return
  }
  
  orderLoading.value = true
  try {
    const orderData = {
      buyer_id: buyerId,
      seller_id: textbook.value.seller_id,
      textbook_id: textbook.value.id,
      price: textbook.value.price,
      buyer_name: orderForm.buyer_name,
      buyer_phone: orderForm.buyer_phone,
      buyer_address: orderForm.buyer_address,
      remark: orderForm.remark
    }
    
    const response = await orderApi.createOrder(orderData)
    if (response.success) {
      ElMessage.success('订单创建成功')
      showOrderDialog.value = false
      router.push('/orders')
    } else {
      ElMessage.error(response.message || '创建订单失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败')
  } finally {
    orderLoading.value = false
  }
}

onMounted(() => {
  loadTextbook()
})
</script>

<style scoped>
.textbook-detail {
  max-width: 1200px;
  margin: 0 auto;
}

.image-container {
  width: 100%;
  height: 500px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.image-container .el-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #909399;
  font-size: 50px;
}

.detail-info {
  padding: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 20px 0;
  color: #303133;
}

.meta-info {
  margin-bottom: 20px;
}

.meta-info p {
  margin: 10px 0;
  color: #606266;
}

.price-info {
  margin: 30px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.current-price {
  font-size: 32px;
  font-weight: bold;
  color: #f56c6c;
  margin-right: 20px;
}

.original-price {
  font-size: 16px;
  color: #909399;
  text-decoration: line-through;
}

.status-info {
  margin-bottom: 20px;
}

.actions {
  margin: 30px 0;
}

.views {
  color: #909399;
  font-size: 14px;
}

.description {
  margin-top: 20px;
}

.description h3 {
  margin-bottom: 15px;
  color: #303133;
}

.description p {
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
}
</style>

